﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Newton
{
    public class ModelAnimation
    {

        public Vector2 StartPosition { get; private set; }

        public Vector2 StartRotation { get; private set; }



        public Vector2 EndPosition { get; private set; }

        public Vector2 EndRotation { get; private set; }



        public Vector2 Position { get; private set; }

        public Vector2 Rotation { get; private set; }



        public TimeSpan Duration { get; private set; }

        public bool Looping { get; private set; }

        public bool AutoReverse { get; private set; }



        TimeSpan elapsedTime = TimeSpan.FromSeconds(0);



        public ModelAnimation(

            Vector2 startposition,

            Vector2 startrotation,

            Vector2 endposition,

            Vector2 endrotation,

            TimeSpan duration,

            bool looping,

            bool autoreverse

            )
        {

            this.StartPosition = startposition;

            this.StartRotation = startrotation;

            this.EndPosition = endposition;

            this.EndRotation = endrotation;

            this.Duration = duration;

            this.Looping = looping;

            this.AutoReverse = autoreverse;

        }



        bool reversing = false;

        public void Update(TimeSpan elapsed)
        {

            this.elapsedTime += elapsed;



            var amount = (float)this.elapsedTime.TotalSeconds / (float)Duration.TotalSeconds;


            if (this.Looping)
            {

                if (amount > 1)
                {

                    this.elapsedTime = TimeSpan.FromSeconds(0);

                    reversing = !reversing;

                    while (amount > 1) amount--;

                }

            }

            else

                amount = MathHelper.Clamp(amount, 0f, 1f);



            if (this.AutoReverse && reversing) amount = 1 - amount;



            Position = Vector2.Lerp(this.StartPosition, this.EndPosition, amount);

            Rotation = Vector2.Lerp(this.StartRotation, this.EndRotation, amount);



        }

    }

}
